# -*- coding: utf8 -*-
import json
import os
import json

from typing import List

from alibabacloud_alimt20181012.client import Client as alimt20181012Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_alimt20181012 import models as alimt_20181012_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_console.client import Client as ConsoleClient
from alibabacloud_tea_util.client import Client as UtilClient


def create_client(
        access_key_id: str,
        access_key_secret: str,
) -> alimt20181012Client:
    """
    使用AK&SK初始化账号Client
    @param access_key_id:
    @param access_key_secret:
    @return: Client
    @throws Exception
    """
    config = open_api_models.Config(
        # 必填，您的 AccessKey ID,
        access_key_id='LTAI5tDUPZfPbT2AvUdWKGQV',
        # 必填，您的 AccessKey Secret,
        access_key_secret='8o3FmXvpRcaxzMWUZbzn1lD1t06DPa'
    )
    # 访问的域名
    config.endpoint = f'mt.cn-hangzhou.aliyuncs.com'
    return alimt20181012Client(config)


def translate(content):
    # client = create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
    #                        os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
    client = create_client('LTAI5tDUPZfPbT2AvUdWKGQV',
                           '8o3FmXvpRcaxzMWUZbzn1lD1t06DPa')
    translate_general_request = alimt_20181012_models.TranslateGeneralRequest(format_type='text',
                                                                              source_language='en',
                                                                              target_language='zh',
                                                                              source_text=content, scene='general')
    runtime = util_models.RuntimeOptions()
    resp = client.translate_general_with_options(translate_general_request, runtime)
    data = json.loads(UtilClient.to_jsonstring(resp.body))
    return data['Data']['Translated']


def format_time(milliseconds):
    # 计算小时、分钟、秒和毫秒
    hours = milliseconds // (1000 * 60 * 60)
    minutes = (milliseconds // (1000 * 60)) % 60
    seconds = (milliseconds // 1000) % 60
    millis = milliseconds % 1000

    # 格式化时间为字符串
    time_str = "{:02d}:{:02d}:{:02d}.{:03d}".format(hours, minutes, seconds, millis)
    return time_str


def generate_srt(subtitles, output_file):
    with open(output_file, "w", encoding="utf-8") as f:
        index = 1
        for subtitle in subtitles:
            start_time = subtitle["start_time"]
            end_time = subtitle["end_time"]
            text = subtitle["text"]

            # 写入字幕序号
            f.write(str(index) + "\n")

            # 写入时间轴
            f.write(f"{start_time} --> {end_time}\n")

            # 写入字幕文本
            f.write(text + "\n\n")

            index += 1


audioResult = '''
{"TaskId": "8d9864354c314a699f8d63550b65effd", "RequestId": "6E1BB477-030A-5F9F-8E2E-487EF6B301B0",
     "StatusText": "SUCCESS", "BizDuration": 788131, "SolveTime": 1688202869909, "RequestTime": 1688201046798,
     "StatusCode": 21050000, "Result": {"Sentences": [{"EndTime": 7900, "SilenceDuration": 0, "BeginTime": 0,
                                                       "Text": "In this video. I will show you how you can make an animated story with chatgpt and art flow dota.i.. ",
                                                       "ChannelId": 0, "SpeechRate": 159, "EmotionValue": 6.5},
                                                      {"EndTime": 12100, "SilenceDuration": 0, "BeginTime": 8240,
                                                       "Text": "First, I will create the story with Chatgpt. ",
                                                       "ChannelId": 0, "SpeechRate": 124, "EmotionValue": 6.5},
                                                      {"EndTime": 31370, "SilenceDuration": 0, "BeginTime": 12380,
                                                       "Text": "I will then use art flow dota.i.to create the images, animation, and voiceover for the story. I open chatgpt and ask him to create a story for me about a ten year old boy who loves to read about the history of the world and thus discovers a magical book that allows him to travel through. ",
                                                       "ChannelId": 0, "SpeechRate": 183, "EmotionValue": 6.5},
                                                      {"EndTime": 50630, "SilenceDuration": 0, "BeginTime": 31690,
                                                       "Text": "So in the next ten days, he travels through time and meets ten great personalities. Such as Leonardo da Vinci, Christopher Columbus, William Shakespeare, Isaac Newton. Albert Einstein, Galileo Galilei, Aristotle, Nicola Tesla, Marie Curie and Charles Darwin. ",
                                                       "ChannelId": 0, "SpeechRate": 120, "EmotionValue": 6.5},
                                                      {"EndTime": 56420, "SilenceDuration": 0, "BeginTime": 50910,
                                                       "Text": "In each encounter with these individuals, he learned something about their great achievements. ",
                                                       "ChannelId": 0, "SpeechRate": 141, "EmotionValue": 6.5},
                                                      {"EndTime": 65240, "SilenceDuration": 0, "BeginTime": 56780,
                                                       "Text": "After his time travel adventure ends, he decides to study hard and hard so that he, too, can be a worthy representative of his time. ",
                                                       "ChannelId": 0, "SpeechRate": 177, "EmotionValue": 6.4},
                                                      {"EndTime": 81620, "SilenceDuration": 11, "BeginTime": 77000,
                                                       "Text": "Once I have the story, I can move on to generating the video. ",
                                                       "ChannelId": 0, "SpeechRate": 168, "EmotionValue": 6.5},
                                                      {"EndTime": 95400, "SilenceDuration": 9, "BeginTime": 91130,
                                                       "Text": "I open art flow dota.i., and select image studio. ",
                                                       "ChannelId": 0, "SpeechRate": 140, "EmotionValue": 6.5},
                                                      {"EndTime": 99060, "SilenceDuration": 0, "BeginTime": 95680,
                                                       "Text": "The first thing I will do is generate the images. ",
                                                       "ChannelId": 0, "SpeechRate": 177, "EmotionValue": 6.5},
                                                      {"EndTime": 102970, "SilenceDuration": 0, "BeginTime": 99500,
                                                       "Text": "I choose a three to two aspect ratio, format. ",
                                                       "ChannelId": 0, "SpeechRate": 155, "EmotionValue": 6.5},
                                                      {"EndTime": 117850, "SilenceDuration": 9, "BeginTime": 112500,
                                                       "Text": "I will now put here the first paragraph of the story that generated chatgpt. ",
                                                       "ChannelId": 0, "SpeechRate": 157, "EmotionValue": 6.5},
                                                      {"EndTime": 124970, "SilenceDuration": 3, "BeginTime": 120960,
                                                       "Text": "Below, I select add style and select an image style. ",
                                                       "ChannelId": 0, "SpeechRate": 149, "EmotionValue": 6.5},
                                                      {"EndTime": 153480, "SilenceDuration": 24, "BeginTime": 149880,
                                                       "Text": "I choose 3d cartoon. And finally, floor. ",
                                                       "ChannelId": 0, "SpeechRate": 133, "EmotionValue": 6.6},
                                                      {"EndTime": 177390, "SilenceDuration": 18, "BeginTime": 171930,
                                                       "Text": "While the images are being generated, I copy the second paragraph of the story. ",
                                                       "ChannelId": 0, "SpeechRate": 153, "EmotionValue": 6.5},
                                                      {"EndTime": 186020, "SilenceDuration": 5, "BeginTime": 183300,
                                                       "Text": "I paced the second paragraph, as well. ",
                                                       "ChannelId": 0, "SpeechRate": 154, "EmotionValue": 6.4},
                                                      {"EndTime": 196980, "SilenceDuration": 5, "BeginTime": 191290,
                                                       "Text": "I really don't like these results. So I choose floor again to generate new images. ",
                                                       "ChannelId": 0, "SpeechRate": 168, "EmotionValue": 6.5},
                                                      {"EndTime": 208950, "SilenceDuration": 7, "BeginTime": 204290,
                                                       "Text": "In the same way, I generate the rest of the images from the story. ",
                                                       "ChannelId": 0, "SpeechRate": 180, "EmotionValue": 6.5},
                                                      {"EndTime": 301180, "SilenceDuration": 90, "BeginTime": 299440,
                                                       "Text": "Once I have the images. ", "ChannelId": 0,
                                                       "SpeechRate": 172, "EmotionValue": 6.5},
                                                      {"EndTime": 305410, "SilenceDuration": 0, "BeginTime": 301350,
                                                       "Text": "I move on to generating the video, by selecting video studio. ",
                                                       "ChannelId": 0, "SpeechRate": 162, "EmotionValue": 6.6},
                                                      {"EndTime": 317710, "SilenceDuration": 9, "BeginTime": 314610,
                                                       "Text": "You can make up to twenty scenes in one video. ",
                                                       "ChannelId": 0, "SpeechRate": 193, "EmotionValue": 6.6},
                                                      {"EndTime": 335040, "SilenceDuration": 11, "BeginTime": 329550,
                                                       "Text": "For the first scene, I select an image, then select dialogue and put the text to it. ",
                                                       "ChannelId": 0, "SpeechRate": 185, "EmotionValue": 6.5},
                                                      {"EndTime": 368140, "SilenceDuration": 30, "BeginTime": 365420,
                                                       "Text": "I also choose the voice to the text. ", "ChannelId": 0,
                                                       "SpeechRate": 176, "EmotionValue": 6.5},
                                                      {"EndTime": 378180, "SilenceDuration": 7, "BeginTime": 375160,
                                                       "Text": "There are many audio options to choose from. ",
                                                       "ChannelId": 0, "SpeechRate": 158, "EmotionValue": 6.5},
                                                      {"EndTime": 382030, "SilenceDuration": 0, "BeginTime": 378460,
                                                       "Text": "You can listen to them before choosing a suitable voice. ",
                                                       "ChannelId": 0, "SpeechRate": 168, "EmotionValue": 6.5},
                                                      {"EndTime": 394310, "SilenceDuration": 7, "BeginTime": 389570,
                                                       "Text": "From effects, I choose the direction of motion of the image in the scene. ",
                                                       "ChannelId": 0, "SpeechRate": 177, "EmotionValue": 6.8},
                                                      {"EndTime": 403420, "SilenceDuration": 5, "BeginTime": 399940,
                                                       "Text": "With that plus here, I move on to the next scene. ",
                                                       "ChannelId": 0, "SpeechRate": 189, "EmotionValue": 6.5},
                                                      {"EndTime": 429310, "SilenceDuration": 21, "BeginTime": 424550,
                                                       "Text": "This is how I arrange the images. text and audio of all the scenes. ",
                                                       "ChannelId": 0, "SpeechRate": 176, "EmotionValue": 6.6},
                                                      {"EndTime": 484430, "SilenceDuration": 50, "BeginTime": 479370,
                                                       "Text": "Once all the scenes are done, I choose export and the animation is done. ",
                                                       "ChannelId": 0, "SpeechRate": 166, "EmotionValue": 6.6},
                                                      {"EndTime": 493940, "SilenceDuration": 7, "BeginTime": 491470,
                                                       "Text": "And now I will show you the result. ", "ChannelId": 0,
                                                       "SpeechRate": 194, "EmotionValue": 6.6},
                                                      {"EndTime": 506040, "SilenceDuration": 1, "BeginTime": 495410,
                                                       "Text": "Once upon a time, in the quiet town of Oakville, there lived a curious and imaginative ten year old boy named Benjamin. Benjamin had a deep love for books. especially those about the history of the world. ",
                                                       "ChannelId": 0, "SpeechRate": 208, "EmotionValue": 7.9},
                                                      {"EndTime": 512790, "SilenceDuration": 1, "BeginTime": 507190,
                                                       "Text": "He would spend hours immersed in tales of great adventures and remarkable people who had shaped the course of history. ",
                                                       "ChannelId": 0, "SpeechRate": 214, "EmotionValue": 7.9},
                                                      {"EndTime": 518090, "SilenceDuration": 1, "BeginTime": 513790,
                                                       "Text": "One sunny day as Benjamin was exploring the attic of his old family house. ",
                                                       "ChannelId": 0, "SpeechRate": 195, "EmotionValue": 8.0},
                                                      {"EndTime": 522320, "SilenceDuration": 0, "BeginTime": 518390,
                                                       "Text": "He stumbled upon a dusty leather bound book tucked away in a forgotten corner, and. ",
                                                       "ChannelId": 0, "SpeechRate": 229, "EmotionValue": 7.9},
                                                      {"EndTime": 527760, "SilenceDuration": 0, "BeginTime": 522770,
                                                       "Text": "Intrigued by its ancient appearance, Benjamin opened the book to find blank pages. ",
                                                       "ChannelId": 0, "SpeechRate": 156, "EmotionValue": 7.9},
                                                      {"EndTime": 536800, "SilenceDuration": 1, "BeginTime": 528790,
                                                       "Text": "However, when he ran his fingers across the pages, a burst of warm light surrounded him and he found himself transported to a different time and place. ",
                                                       "ChannelId": 0, "SpeechRate": 202, "EmotionValue": 8.0},
                                                      {"EndTime": 542930, "SilenceDuration": 1, "BeginTime": 537880,
                                                       "Text": "To his amazement. Benjamin realized that this magical book allowed him to travel through time. ",
                                                       "ChannelId": 0, "SpeechRate": 178, "EmotionValue": 7.9},
                                                      {"EndTime": 552790, "SilenceDuration": 0, "BeginTime": 543900,
                                                       "Text": "Excitement filled his heart as he embarked on a thrilling journey spanning over ten days to meet ten extraordinary personalities who had changed the world. ",
                                                       "ChannelId": 0, "SpeechRate": 168, "EmotionValue": 7.9},
                                                      {"EndTime": 560380, "SilenceDuration": 1, "BeginTime": 553880,
                                                       "Text": "On the first day, Benjamin found himself in Renaissance Italy, standing before the brilliant Leonardo da Vincy. ",
                                                       "ChannelId": 0, "SpeechRate": 156, "EmotionValue": 7.9},
                                                      {"EndTime": 568690, "SilenceDuration": 0, "BeginTime": 560900,
                                                       "Text": "Leonardo shared his artistic genius and taught Benjamin the importance of embracing curiosity and creativity in all aspects of life. ",
                                                       "ChannelId": 0, "SpeechRate": 154, "EmotionValue": 8.0},
                                                      {"EndTime": 580620, "SilenceDuration": 1, "BeginTime": 569760,
                                                       "Text": "Day two brought Benjamin aboard Christopher Columbus's ship, where he learned about the explorer's determination and courage in discovering new lands. even when faced with uncertainty and. ",
                                                       "ChannelId": 0, "SpeechRate": 160, "EmotionValue": 7.9},
                                                      {"EndTime": 592210, "SilenceDuration": 1, "BeginTime": 581690,
                                                       "Text": "In Elizabethan England. Benjamin met the great playwright William Shakespeare. who inspired him to appreciate the beauty of words and storytelling. reminding him that the pen is indeed, mightier than the sword. ",
                                                       "ChannelId": 0, "SpeechRate": 182, "EmotionValue": 8.0},
                                                      {"EndTime": 595900, "SilenceDuration": 1, "BeginTime": 593300,
                                                       "Text": "Day four took Benjamin to Isaac Newton study. ",
                                                       "ChannelId": 0, "SpeechRate": 184, "EmotionValue": 7.9},
                                                      {"EndTime": 601070, "SilenceDuration": 0, "BeginTime": 596180,
                                                       "Text": "Where he witnessed the apple for and learned about the wonders of gravity and the laws of motion. ",
                                                       "ChannelId": 0, "SpeechRate": 220, "EmotionValue": 7.9},
                                                      {"EndTime": 606840, "SilenceDuration": 0, "BeginTime": 601920,
                                                       "Text": "Newton's insatiable thirst for knowledge inspired Benjamin to question the world around him. ",
                                                       "ChannelId": 0, "SpeechRate": 170, "EmotionValue": 8.0},
                                                      {"EndTime": 616920, "SilenceDuration": 1, "BeginTime": 607880,
                                                       "Text": "Next, Benjamin found himself in the presence of the brilliant scientist Albert Einstein, who introduced him to the wonders of relativity and the power of imagination. ",
                                                       "ChannelId": 0, "SpeechRate": 172, "EmotionValue": 8.0},
                                                      {"EndTime": 620860, "SilenceDuration": 0, "BeginTime": 617390,
                                                       "Text": "Einstein taught Benjamin that anything was possible. if he could dream it. ",
                                                       "ChannelId": 0, "SpeechRate": 207, "EmotionValue": 7.9},
                                                      {"EndTime": 627580, "SilenceDuration": 1, "BeginTime": 621940,
                                                       "Text": "Day six transported Benjamin to Italy again. But this time he met Galileo, Galileo. ",
                                                       "ChannelId": 0, "SpeechRate": 148, "EmotionValue": 7.9},
                                                      {"EndTime": 637420, "SilenceDuration": 0, "BeginTime": 628380,
                                                       "Text": "Galileo's unwavering belief in scientific observation and the pursuit of truth encouraged Benjamin to question established ideas and seek evidence in everything he learned. ",
                                                       "ChannelId": 0, "SpeechRate": 165, "EmotionValue": 8.0},
                                                      {"EndTime": 643900, "SilenceDuration": 1, "BeginTime": 638490,
                                                       "Text": "On day seven. Benjamin travelled back to ancient Greece and met Aristotle, the great philosopher. ",
                                                       "ChannelId": 0, "SpeechRate": 166, "EmotionValue": 7.9},
                                                      {"EndTime": 654250, "SilenceDuration": 0, "BeginTime": 644300,
                                                       "Text": "Aristotle emphasized the importance of critical thinking. logic, and the pursuit of knowledge, teaching Benjamin to examine the world with an open and curious mind. ",
                                                       "ChannelId": 0, "SpeechRate": 150, "EmotionValue": 8.0},
                                                      {"EndTime": 662610, "SilenceDuration": 1, "BeginTime": 655310,
                                                       "Text": "Inventor and electrical genius Nikola Tesla greeted Benjamin on day eight. demonstrating the incredible power of electricity. ",
                                                       "ChannelId": 0, "SpeechRate": 139, "EmotionValue": 7.9},
                                                      {"EndTime": 670820, "SilenceDuration": 0, "BeginTime": 663130,
                                                       "Text": "Tesla is boundless imagination and dedication to scientific progress inspired Benjamin to think beyond boundaries and embrace innovation. ",
                                                       "ChannelId": 0, "SpeechRate": 140, "EmotionValue": 8.0},
                                                      {"EndTime": 678710, "SilenceDuration": 1, "BeginTime": 671880,
                                                       "Text": "On day nine. Benjamin met Marie Curie, the pioneering scientist who discovered radium and polonium. ",
                                                       "ChannelId": 0, "SpeechRate": 131, "EmotionValue": 7.9},
                                                      {"EndTime": 688770, "SilenceDuration": 1, "BeginTime": 680380,
                                                       "Text": "Maurice, unwavering determination and dedication to her research showed Benjamin the value of persistence and hard work in achieving great things. ",
                                                       "ChannelId": 0, "SpeechRate": 150, "EmotionValue": 8.0},
                                                      {"EndTime": 692990, "SilenceDuration": 1, "BeginTime": 689820,
                                                       "Text": "Finally, on the last day of his time travel adventure. ",
                                                       "ChannelId": 0, "SpeechRate": 189, "EmotionValue": 7.9},
                                                      {"EndTime": 697780, "SilenceDuration": 0, "BeginTime": 693270,
                                                       "Text": "Benjamin found himself in the company of Charles Darwin, the renowned naturalist. ",
                                                       "ChannelId": 0, "SpeechRate": 159, "EmotionValue": 7.9},
                                                      {"EndTime": 707630, "SilenceDuration": 0, "BeginTime": 698580,
                                                       "Text": "Darwin's exploration of the natural world and his theory of evolution taught Benjamin about the interconnectedness of all living things and the importance of Priscilla. ",
                                                       "ChannelId": 0, "SpeechRate": 172, "EmotionValue": 7.9},
                                                      {"EndTime": 715050, "SilenceDuration": 0, "BeginTime": 708430,
                                                       "Text": "After his incredible journey through time, Benjamin returns to his own era, filled with newfound knowledge and inspiration. ",
                                                       "ChannelId": 0, "SpeechRate": 163, "EmotionValue": 8.0},
                                                      {"EndTime": 719930, "SilenceDuration": 0, "BeginTime": 715330,
                                                       "Text": "He knew that he had a duty to honor the legacy of those great personalities he had encountered. ",
                                                       "ChannelId": 0, "SpeechRate": 234, "EmotionValue": 7.9},
                                                      {"EndTime": 732770, "SilenceDuration": 1, "BeginTime": 721070,
                                                       "Text": "And so the story of Benjamin, the time travelling reader, became a tale that would inspire young minds to dream big, explore their passions, and understand the power of knowledge in shaping the world around them. ",
                                                       "ChannelId": 0, "SpeechRate": 184, "EmotionValue": 7.9},
                                                      {"EndTime": 745210, "SilenceDuration": 9, "BeginTime": 742310,
                                                       "Text": "I can also download the video from here. ",
                                                       "ChannelId": 0, "SpeechRate": 165, "EmotionValue": 6.6},
                                                      {"EndTime": 747790, "SilenceDuration": 0, "BeginTime": 745770,
                                                       "Text": "I think it turned out well. ", "ChannelId": 0,
                                                       "SpeechRate": 178, "EmotionValue": 6.5},
                                                      {"EndTime": 755620, "SilenceDuration": 0, "BeginTime": 748270,
                                                       "Text": "I don't like all the images, but I think if I experiment more, especially with the prompts, I might get better results. ",
                                                       "ChannelId": 0, "SpeechRate": 187, "EmotionValue": 6.5},
                                                      {"EndTime": 770320, "SilenceDuration": 0, "BeginTime": 756040,
                                                       "Text": "This tool is very easy to use. and I plan to experiment with it for other applications as well. For example, I'll try to create consistent character images in mid journey. Upload them here and see how the story will look like. ",
                                                       "ChannelId": 0, "SpeechRate": 180, "EmotionValue": 6.5},
                                                      {"EndTime": 772900, "SilenceDuration": 0, "BeginTime": 770620,
                                                       "Text": "Or to make shorts for Youtube. ", "ChannelId": 0,
                                                       "SpeechRate": 157, "EmotionValue": 6.4},
                                                      {"EndTime": 776730, "SilenceDuration": 0, "BeginTime": 773310,
                                                       "Text": "Friends, don't miss out on my latest content. ",
                                                       "ChannelId": 0, "SpeechRate": 157, "EmotionValue": 6.5},
                                                      {"EndTime": 783760, "SilenceDuration": 0, "BeginTime": 777240,
                                                       "Text": "Hit the subscribe button and click the notification bell to be the first to know when I upload a new video. ",
                                                       "ChannelId": 0, "SpeechRate": 193, "EmotionValue": 6.5},
                                                      {"EndTime": 787560, "SilenceDuration": 0, "BeginTime": 784290,
                                                       "Text": "Thank you for watching this video, and see you soon. ",
                                                       "ChannelId": 0, "SpeechRate": 183, "EmotionValue": 6.6}]
                                                       }}
'''
loads = json.loads(audioResult)
print(loads['Result'])
print(loads['Result']['Sentences'])
# print(loads)
srt = []
cnSrt = []
for i in loads['Result']['Sentences']:
    BeginTime_ = format_time(i['BeginTime'])
    EndTime_ = format_time(i['EndTime'])
    Text_ = i['Text']
    c = {'start_time': BeginTime_, 'end_time': EndTime_, 'text': Text_}
    srt.append(c)
    translate1 = translate(Text_)
    cn = {'start_time': BeginTime_, 'end_time': EndTime_, 'text': translate1}
    cnSrt.append(cn)
generate_srt(srt, 'output.srt')
generate_srt(cnSrt, 'outputCn.srt')
